package com.shop.shopmall.config;

import com.shop.shopmall.filter.JwtAuthenticationTokenFilter;
import com.shop.shopmall.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * spring security 配置
 * @author jamie
 */
@Configuration
@EnableMethodSecurity
public class SecurityConfig {

    @Autowired
    UserServiceImpl userService;

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring().requestMatchers("/admin/login", "/sso/login");
    }

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        // 配置接口鉴权策略
        httpSecurity.authorizeHttpRequests((authorize) -> authorize
                .requestMatchers("/admin/login", "/admin/validCode","/uploads/**").permitAll()
                .anyRequest().authenticated()
        );
        // CSRF 禁用，因为不使用 Session
        httpSecurity.csrf(AbstractHttpConfigurer::disable);
        // 基于 token 机制，不需要 Session
        httpSecurity.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
        // 设置登录
        httpSecurity.userDetailsService(userService);
        // 权限不足
        httpSecurity.exceptionHandling((exceptionHandling) -> exceptionHandling.accessDeniedHandler(
                (request, response, accessDeniedException) -> {
                    response.setContentType("application/json;charset=utf-8");
                    response.getWriter().write("{\"code\":403,\"msg\":\"权限不足\"}");
                    response.getWriter().flush();
                    response.getWriter().close();
                }
        ));
        // 添加 JWT 过滤器
        httpSecurity.addFilterBefore(new JwtAuthenticationTokenFilter(userService), UsernamePasswordAuthenticationFilter.class);
        // 添加 CORS 配置
        httpSecurity.cors(Customizer.withDefaults());
        return httpSecurity.build();
    }

}
